<?php

namespace App\Http\Controllers\Front;

use App\Http\Controllers\Controller;
use App\Http\Service\MessageService;
use App\Model\ArticleFavorite;
use App\Model\Articles;
use App\User;
use Illuminate\Support\Facades\Auth;
use Swagger\Annotations as SWG;

class ArticleFavoriteController extends Controller
{
    /**
     * @var User
     */
    private $user;

    public function __construct()
    {
        $this->user = Auth::user();
    }

    /**
     * @SWG\Get(
     *     path="/front/articles/favorite",
     *     tags={"用户相关"},
     *     summary="用户收藏文章列表",
     *     description="用户收藏文章列表",
     *     produces={"application/json"},
     *     @SWG\Parameter(ref="#/parameters/auth"),
     *     @SWG\Parameter(name="offset", in="query", type="integer", description="起始"),
     *     @SWG\Parameter(name="keyword", in="query", type="integer", description="搜索"),
     *     @SWG\Response(
     *          response="200",
     *          description="文章列表",
     *          @SWG\Schema(
     *              @SWG\Property(property="count", type="integer", description="总数"),
     *              @SWG\Property(
     *                  property="data",
     *                  type="array",
     *                  @SWG\Items(
     *                      @SWG\Property(property="id", type="integer", description="文章id"),
     *                      @SWG\Property(property="title", type="string", description="文章标题"),
     *                      @SWG\Property(property="cover", type="string", description="文章封面"),
     *                      @SWG\Property(property="pageviews", type="integer", description="浏览量"),
     *                      @SWG\Property(property="created_at", type="string", format="date", description="发布时间"),
     *                  )
     *              )
     *          )
     *      )
     * )
     */
    public function index()
    {
        $articleM = ArticleFavorite::where('article_favorite.user_id', $this->user->id);
        $articleM->select('a.title','a.id','a.cover as cover','a.pageviews','a.created_at', 'mu.account as author');
        if (request()->has('name')){
            $articleM->where('a.title', 'like', '%'.request('name').'%');
        }
        $articleM->leftJoin('articles as a', 'a.id','=','article_favorite.article_id');
        $articleM->leftJoin('media_user_info as mu', 'mu.media_user_id','=','a.author');
        if (request()->has('keyword')) {
            $articleM->where('a.title', 'like', '%'.request('keyword').'%');
        }
//        $articles = $articleM->paginate();
//        $data = $articles->toArray();
//        $data['data'] = [];
//        foreach ($articles as $article){
//            $a = $article->article;
//            if (is_null($a)){
//                continue;
//            }
//            $data['data'][] = [
//                'article_id' => $a->id,
//                'title' => $a->title,
//                'image' => $a->cover_path,
//                'page_view' => $a->page_view,
//                'created_at' => $a->created_at->format('Y-m-d H:i:s')
//            ];
//        }
        $data = [];
        if (request()->has('offset')) {
            $data['count'] = $articleM->count();
            $data['data'] = $articleM->offset(request('offset', 1))->limit(request('limit', 10))->get();
        }else{
            $data = $articleM->paginate(request('limit', 15));
        }


        return $this->renderJson($data);
    }

    /**
     * @SWG\Post(
     *     path="/front/articles/{id}/favorite",
     *     tags={"文章相关"},
     *     summary="收藏文章",
     *     description="收藏文章",
     *     produces={"application/json"},
     *     @SWG\Parameter(ref="#/parameters/auth"),
     *     @SWG\Parameter(name="id", in="path", required=true, type="integer", description="文章id"),
     *     @SWG\Response(
     *          response="200",
     *          description="收藏成功"
     *      )
     * )
     */
    public function store($id)
    {
        //2018.8.15 新增非会员只能收藏10次
        if (!User::is_vip(Auth::id())){
            $n = ArticleFavorite::where('user_id', $this->user->id)->count();
            if ($n >= 10){
                return $this->fail('开通会员，无限收藏哦!');
            }
        }
        $old = ArticleFavorite::where('article_id', $id)->where('user_id', $this->user->id)->first();
        if ($old != null){
            return $this->fail('你已经收藏过了');
        }
        $r = ArticleFavorite::create(['article_id' => $id, 'user_id' => $this->user->id]);
        if (!$r){
            return $this->error('收藏失败');
        }
        $article = Articles::find($id);
        if (is_null($article)){
            return $this->fail('文章不存在');
        }
        $article->increment('collect_num');//收藏数量++
        if ($article->author != 0){
            MessageService::message($this->user->id, $article->author, 5, $article->id);
        }
        return $this->success();
    }

    /**
     * @SWG\Delete(
     *     path="/front/articles/favorite",
     *     tags={"用户相关"},
     *     summary="删除收藏文章",
     *     description="删除收藏文章",
     *     produces={"application/json"},
     *     @SWG\Parameter(ref="#/parameters/auth"),
     *     @SWG\Parameter(name="ids", in="formData", required=true, type="string", description="文章id数组"),
     *     @SWG\Response(
     *          response="200",
     *          description="删除成功"
     *      )
     * )
     */
    public function destroy()
    {
        $ids = request('ids');
        $article = ArticleFavorite::whereIn('article_id', $ids)->where('user_id', $this->user->id)->first();
        if ($article == null){
            return $this->fail('文章未收藏');
        }
        $r = $article->delete();
        if ($r){
            Articles::whereIn('id', $ids)->decrement('collect_num');//收藏数量--
            return $this->success();
        }
        return $this->error();
    }
}
